export default {
    namespaced: true,
    state: {//仓库
        data:null,
        isInit:false,
        site:{},
    },
    //计算
    getters: {
        product(state){
            let list = [];
            if(state.data && !state.data.link){
                let product = state.data.product.split("@");
                product.filter((item)=>{
                    let i = item.split(",");
                    if(i.length > 1){
                        list.push(i)
                    }
                });
            }else if(state.data && state.data.link){
               state.data.product[0].filter((item,i)=>{
                    if((state.data.product[0].length -1) === i){

                    }else{
                        list.push(item);
                    }
               })
            }
            return list;
        },
    },
    //更改仓库
    mutations: {
        _setOrderDetail(state,payload){//把刚刚添加的商品添加到data
            state.data = payload;
            state.isInit = true;
        },
        _site(state,payload){
            state.site = payload;
        }
    },
    //异步请求
    actions: {
        addOrderDetail({state,commit, rootState: {$http}}, payload){
            let product = "";//保存商品数据用@分隔
            payload.product.item.filter((item)=>{
                if(payload.product.item.length === 1){
                    product += item.img+","+item.name+","+item.num+","+item.price;
                }else{
                    product += item.img+","+item.name+","+item.num+","+item.price+"@";
                }
            });
            //图片，名字，数量，价格
            let data = {};
            data.user = payload.user;
            data.time = payload.time;
            data.siteId = payload.siteId;
            data.cartId = payload.cartId;
            data.serialNumber = payload.serialNumber;
            data.product = product;
            $http.post("/order/addOrderDetail",{data})//键值相同简写
                .then(result => {
                    //把刚刚添加完的商品放到仓库
                    commit("_setOrderDetail",result.data);
                    //成功之后发送ajax把成为订单的购物车数据删除
                    for(let i=0;i<data.cartId.length;i++){
                        $http.post("/cart/del", {id:data.cartId[i]})
                            .then(result => {
                                //console.log("删除购物车成功");
                            });
                    }
                });
        },
        getSite({state,commit, rootState: {$http}}, payload){
            $http.post("/order/oneSite",{id:payload})
                .then(result => {
                    commit("_site",result.data[0]);
                    console.log(result.data[0]);
                });
        }
    }
};